package com.shijie.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import me.chanjar.weixin.common.exception.WxErrorException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shijie.core.AbstractService;
import com.shijie.domain.entity.Talents;
import com.shijie.domain.entity.Users;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.domain.vo.BaseUserVo;
import com.shijie.mapper.TalentsMapper;
import com.shijie.mapper.UsersMapper;
import com.shijie.utils.CommonUtil;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class UsersService extends AbstractService<Users> {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private TalentsMapper talentsMapper;

    @Autowired
    private WxMaService wxService;
    

    public Users login(String code) throws WxErrorException {
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxService.getUserService().getSessionInfo(code);

        Example condition = new Example(Users.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("openId", wxMaJscode2SessionResult.getOpenid()).andNotEqualTo("status", EnumInterface.Status.INVALID.ordinal());

        List<Users> users = usersMapper.selectByCondition(condition);
        if (null != users && users.size() > 0) {
            // 默认只有一个用户
            Users updateUser = users.get(0);
            updateUser.setLoginDate(new Date());
            updateUser.setLoginIp(CommonUtil.getClientIp());
            usersMapper.updateByConditionSelective(updateUser,condition);
            return updateUser;
        } else {
            Users insertUser = new Users();
            insertUser.setUnionId(wxMaJscode2SessionResult.getUnionid());
            insertUser.setOpenId(wxMaJscode2SessionResult.getOpenid());
            insertUser.setLoginDate(new Date());
            insertUser.setStatus(0);
            insertUser.setLoginIp(CommonUtil.getClientIp());
            insertUser.setCreateTime(new Date());
            insertUser.setCreateBy(insertUser.getNickName());
            usersMapper.insertSelective(insertUser);

            Talents talent = new Talents(insertUser);
            talent.setUserType(EnumInterface.UserType.USER.ordinal());
            talent.setCreateTime(new Date());
            talent.setCreateBy(insertUser.getNickName());
            talentsMapper.insertSelective(talent);

            return insertUser;
        }
    }

    public Users updateUser(String nickname, String avatar, Integer sex, BaseUserVo userCache) {
        Users user = usersMapper.selectByPrimaryKey(userCache.getId());
        if (StringUtils.isEmpty(user.getNickName())) {
            user.setAvatar(avatar);
            user.setNickName(nickname);
            usersMapper.updateByPrimaryKey(user);
/*
 * 			达人的分类sex非微信的数据
 * 
            Example condition = new Example(Talents.class);
            Example.Criteria criteria = condition.createCriteria().andEqualTo("userId", userCache.getId());
            Talents talent = new Talents();

            talent.setUpdateBy(userCache.getNickName());
            talent.setUpdateTime(new Date());
            talent.setSex(sex);
            talentsMapper.updateByConditionSelective(talent, condition);*/
            // TODO 刷新缓存数据
        }
        return user;
    }

    @Transactional
    public void update(Users user) {
        usersMapper.updateByPrimaryKeySelective(user);
        Talents talent = new Talents(user);
        Example condition = new Example(Talents.class);
        Example.Criteria criteria = condition.createCriteria().andEqualTo("userId", user.getId());
        talent.setUpdateBy(user.getNickName());
        talent.setUpdateTime(new Date());
        //普通用户转达人，设置为绑定
		if (talent.getUserType() == 1) {
			talent.setIsBind(1);
		}
        talentsMapper.updateByConditionSelective(talent, condition);
    }
    
    public void updateByPrimaryKeySelective(Users user){
    	 usersMapper.updateByPrimaryKeySelective(user);
	    Talents talent = new Talents(user);
        talent.setUserType(EnumInterface.UserType.USER.ordinal());
        talent.setCreateTime(new Date());
        talent.setCreateBy(user.getNickName());
        Condition condition = new Condition(Talents.class);
        condition.createCriteria().andEqualTo("userId", user.getId());
        talentsMapper.updateByConditionSelective(talent, condition);
    }
    
    public PageInfo<Users> selectUsersByAll(int page,int pageSize,Users user) {
        PageHelper.startPage(page, pageSize);
        List<Users> list = usersMapper.selectUsersByAll(user);
        PageInfo<Users> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    public Users getUserDetail(Integer userId) {
        return usersMapper.detailForUser(userId);
    }

}
